package org.ww.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.ww.commonutils.R;
import org.ww.servicebase.exceptionhandler.GuliException;
import org.ww.vod.service.VodService;
import org.ww.vod.utils.ConstantsVodUtil;
import org.ww.vod.utils.InitVodClient;

import java.util.List;

@RestController
@RequestMapping("/vod/video")
//@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;

    //上传视频到阿里云
    @PostMapping("/uploadVod")
    public R uploadVod(MultipartFile file){
        String videoId = vodService.uploadVod(file);
        return R.ok().data("videoId",videoId);
    }

    //删除阿里云视频
    @DeleteMapping("/removeVod/{id}")
    public R removeVod(@PathVariable String id){
        //根据id删除阿里云视频
        try{
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantsVodUtil.ACCESS_KEY_ID, ConstantsVodUtil.ACCESS_KEY_SECRET);
            //创建删除视频request对象
            DeleteVideoRequest request=new DeleteVideoRequest();
            //向request中设置视频id
            request.setVideoIds(id);
            //调用初始化对象的方法实现删除
            client.getAcsResponse(request);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"删除视频失败！");
        }
    }

    //批量删除视频
    @DeleteMapping("/delete-batch")
    public R deleteBatch(@RequestParam("videoIds") List<String> videoIds){
        vodService.deleteBatch(videoIds);
        return R.ok();
    }

    //根据视频id获取播放凭证
    @GetMapping("/getVideoPlayAuth/{id}")
    public R getVideoPlayAuth(@PathVariable String id){
        try{
            //创建初始化对象
            DefaultAcsClient client=InitVodClient.initVodClient(ConstantsVodUtil.ACCESS_KEY_ID,ConstantsVodUtil.ACCESS_KEY_SECRET);
            //创建获取凭证request和response对象
            GetVideoPlayAuthRequest request=new GetVideoPlayAuthRequest();
            //向request中设置id
            request.setVideoId(id);
            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        }catch (Exception e){
            throw new GuliException(20001,"获取凭证失败");
        }
    }

}
